package day01;

import java.util.Iterator;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/11 13:59
 */
public class ArrayQueue03<E> implements Queue<E>, Iterable<E> {
    private final E[] array;
    private int head = 0;
    private int tail = 0;

    @SuppressWarnings("all")
    public ArrayQueue03(int capacity) {
        // 1. 抛异常
        // 2. 改成2的n次方 2^n
        /*if ((capacity & capacity - 1) != 0) {
            throw new IllegalArgumentException("capacity 必须是2的幂次方");
        }*/
        int n = (int)(Math.log10(capacity - 1) / Math.log10(2)) + 1;
        array = (E[]) new Object[1 << n];
    }

    @Override
    public boolean offer(E val) {
        if (isFull()) {
            return false;
        }
        // array[tail % array.length] = val;
        array[tail & (array.length - 1)] = val;
        tail++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        // E val = array[head % array.length];
        E val = array[head & (array.length - 1)];
        head++;
        return val;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        // return array[head % array.length];
        return array[head & (array.length - 1)];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return tail - head == array.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;
            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                // E val = array[p % array.length];
                E val = array[p & (array.length - 1)];
                p++;
                return val;
            }
        };
    }
}
